<template>
    <!-- <div :class='$style.top'>
        <BLocale />
    </div> -->
    <div :class='$style.page'>
        <div :class='$style.container'>
            <template v-if="!initpwd">
              <!-- <img :class="$style.logo" src="@/assets/whitelogo.png" /> -->
              <div :class="$style.name">欢迎登录</div>
              <div :class='$style.modal'>
                  <div :class='[$style.errorTips, {[$style.show] : error.show}]'>
                      <a-alert :closable='false' :message='error.msg' type='error' show-icon />
                  </div>
                  <a-form :model='formData' layout='vertical'>
                      <a-form-item label='账号'>
                          <a-input type='text' size='large' v-model:value='formData.account' @focus='focus("account")' @keyup.enter="login" />
                      </a-form-item>
                      <a-form-item label='密码'>
                          <a-input-password size='large' v-model:value='formData.password' @focus='focus("password")' @keyup.enter="login" />
                      </a-form-item>
                      <a-form-item>
                          <a-button size='large' type="primary" block :loading='loading' @click='login'>登录</a-button>
                      </a-form-item>
                  </a-form>
              
              </div>
            </template>
            <template v-else>
              <div :class='$style.loginText'>重置初始密码</div>
              <div :class='$style.modal'>
                  <a-form ref="changePwdForm" layout="vertical" :model="changePwd">
                      <a-form-item label="旧密码" name="oldpassword" required :rules="[{required : true, message : $c('please', 'input', 'password')}]">
                          <a-input type="password" v-model:value="changePwd.oldpassword" :maxlength="30" show-count />
                      </a-form-item>
                      <a-form-item label="新密码" name="password" required :rules="pwdRules">
                          <a-input type="password" v-model:value="changePwd.password" :maxlength="30" show-count />
                      </a-form-item>
                      <a-form-item label="确认新密码" name="rpassword" required :rules="rpwdRules">
                          <a-input type="password" v-model:value="changePwd.rpassword" :maxlength="30" show-count />
                      </a-form-item>
                      <a-form-item>
                          <a-button size='large' type="primary" block :loading='loading' @click='submitChangePwd'>{{$t('confirm')}}</a-button>
                      </a-form-item>
                  </a-form>
              
              </div>
            </template>
        </div>
    </div>
  
  </template>
  
  <script lang='ts' setup>
    import { reactive, ref } from "vue"
    import { loginApi, loginInitApi } from '@/api/Login'
    import { useAuthStore } from '@/store'
    import { useI18nStore } from '@/store/i18n'
    import { useRoute, useRouter } from "vue-router"
  import { message, Modal } from "ant-design-vue"
  
  
    const prevTenantKey = 'prevTenant'
    const prevAccountKey = 'prevAccount'
  
  
    const initpwd = ref(false)
  
  
    let prevTenant = localStorage.getItem(prevTenantKey)
    let prevAccount = localStorage.getItem(prevAccountKey)
  
    const router = useRouter()
  
    const auth = useAuthStore()
  
    const i18n = useI18nStore()
  
    const error = reactive({
        msg : '',
        key : '',
        show : false
    })
  
    const loading = ref(false)
  
    const formData = ref({
        merchant : prevTenant ? prevTenant : '',
        account : prevAccount ? prevAccount : '',
        password : '',
    })
    
  
    function focus(key:string) {
        if(error.key == '' || key == error.key) {
            error.show = false
            error.key = ''
        }
    }
  
  
  
    async function login() {
        if(formData.value.account === '') {
            error.msg = '请输入账号'
            error.key = 'account'
            error.show = true
            return
        }
        if(formData.value.password === '') {
            error.msg = '请输入密码'
            error.key = 'password'
            error.show = true
            return
        }
  
  
        error.show = false
  
        loading.value = true
  
        const params:any = {
            ...formData.value
        }
  
  
        doLogin(params.account, params.password)
        
    }
  
    async function doLogin(account:string, password:string) {
      loading.value = true
      const res = await loginApi({account, password})
        
        if(res.success) {
        //   if(res.data.pwd == false) {
        //     loading.value = false
        //       message.warn('为了您的账号安全，请重置密码')
        //       initpwd.value = true
        //       return
        //   }
          
            handleLogin(res.data)
        }else {
            loading.value = false
            error.msg = res.msg
  
            if(res.code == 401) {
                error.msg += ('，今天登陆次数剩下' + res.data + '次')
            }
  
            error.show = true
        }
    }
  
    
    function handleLogin(data) {
        //localStorage.setItem(prevTenantKey, formData.value.merchant)
        localStorage.setItem(prevAccountKey, formData.value.account)
        auth.handleLoginData(data)
        auth.refresh()
        router.replace('/')
    }
  
  
  
    const changePwdForm = ref()
      const changePwd = ref({
          oldpassword : '',
          password : '',
          rpassword: '',
      })
  
      const pwdRules = [
          {
              required : true,
              validator(rule, value) {
  
                  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/;
  
                  if(!regex.test(value)) {
                      return Promise.reject('密码必须同时包含大小写字母和数字，且不少于8位')
                  }
  
  
                  return Promise.resolve()
              }
          }
      ]
  
      const rpwdRules = [
          {
              required : true,
              validator(rule, value) {
  
                  if(value != changePwd.value.password) {
                      return Promise.reject('前后密码不一致')
                  }
  
  
                  return Promise.resolve()
              }
          }
      ]
  
      async function submitChangePwd() {
          let params  = await changePwdForm.value.validate()
          loading.value = true
          loginInitApi({account: formData.value.account, oldpassword:params.oldpassword, password:params.password}).then(res => {
              
              if(res.success) {
                  doLogin(formData.value.account, params.password)
              }else {
                  loading.value = false
                  Modal.error({
                      title : res.msg
                  })
              }
          })
      }
  </script>
  
  <style module lang='scss'>

    .logo{
        display: block;
        margin: auto;
    }
    .name{
        color: #333;
        font-size: 32px;
        text-align: center;
        margin-top: 20px;
    }

    .top{
        width: 1200px;
        max-width: 100%;
        position: absolute;
        top: 25px;
        left: 50%;
        transform: translateX(-50%);
        display: flex;
        justify-content: right;
    }
  
    .page{
        height: 100vh;
        width: 100vw;
        //background: no-repeat center url("@/assets/login-bc.jpg");
    }
  
    .container{
        position: fixed;
        left: 50%;
        top: 40%;
        transform: translate(-50%, -50%);
  
        .loginText{
            text-align: center;
            font-size: 18px;
            color: #fff;
        }
        
        .modal {
            width: 500px;
            box-shadow: 0 0 12px 1px #e8e8e8;
            background-color: #fff;
            margin-top: 30px;
            padding: 30px 30px;
  
            @media screen and (max-width:500px) {
                width: 300px;
            }
        }
    }
  
    .errorTips {
        margin-bottom: 15px;
        display: none;
  
        &.show{
            display: block;
        }
    }
  </style>